<template>
  <a-drawer
      title="取消匹配"
      :maskClosable="true"
      :visible="visible"
      :width="$store.getters.isMobile ? 350 : 600"
      :body-style="{ paddingBottom: '80px' }"
      @close="onCancel"
  >
    <a-alert type="info" v-if="!processApprove" style="margin-bottom: 10px;">
      <template #message>
        取消匹配流水暂未开启审批，点击”
        <span v-if="Approveis_admin" class="link" @click.stop="goSetting">配置</span>
        <span v-else class="link" style="cursor: not-allowed;">配置</span>
        “可快速设置。
      </template>
    </a-alert>
    <a-alert type="info" show-icon v-if="content.receiptListNumber">
      <template #message>
        <span>当前账单已开据收据，请谨慎进行操作</span>
      </template>
    </a-alert>
    <a-form layout="vertical" class="mt-10">
      <a-form-item label="日期" v-bind="validateInfos.cancel_match_date">
        <a-date-picker
            class="w-100p"
            v-model:value="modelRef.cancel_match_date"
            :valueFormat="dateFormatStr"
            :disabled-date="disabledDate"
        />
      </a-form-item>
      <a-form-item v-if="processApprove" label="审批备注">
        <a-textarea
            v-model:value="modelRef.approval_remark"
            :auto-size="{ minRows: 3, maxRows: 6 }"
        />
      </a-form-item>
    </a-form>
    <div class="drawer-footer">
      <a-space>
        <a-button @click.prevent="onCancel">取消</a-button>
        <a-button v-if="processApprove" type="primary" @click.prevent="showConfirm"> 保存&发起审批
        </a-button>
        <a-button v-else type="primary" :loading="submitLoading" @click.prevent="onSubmit"> 确定
        </a-button>
      </a-space>
    </div>
  </a-drawer>
</template>

<script>
import {defineComponent, reactive, ref, toRefs, watch, createVNode} from "vue";
import request from "../../../../common/utils/request";
import moment from "moment";
import {Form, message, Modal} from "ant-design-vue";

const useForm = Form.useForm;
import {ExclamationCircleOutlined} from '@ant-design/icons-vue';
import store from "@/store";

const dateFormatStr = "YYYY-MM-DD";

export default defineComponent({
  name: "CancelMatch",
  components: {ExclamationCircleOutlined},
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    content: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  setup(props, context) {
    const state = reactive({
      // 是否有审批
      processApprove: true,
      Approveis_admin: false,
      Approve_id: 0,

      submitLoading: false,
      Closeflow: false,
    });

    const disabledDate = (current) => {
      return current < moment(props.content.match_date).startOf("day");
    };
    const modelRef = reactive({
      cancel_match_date: "",
      approval_remark: "",
    });
    const ruleRef = reactive({
      cancel_match_date: [{required: true, message: "必选"}],
    });

    const {resetFields, validate, validateInfos} = useForm(modelRef, ruleRef);
    const onCancel = () => {
      context.emit("cancel");
    };

    const showConfirm = () => {
      Modal.confirm({
        title: '确定解除流水和账单的匹配?',
        icon: createVNode(ExclamationCircleOutlined),
        okText: '解除流水',
        cancelText: '解除并关闭流水',
        onOk() {
          state.Closeflow = false
          onSubmit()
        },
        onCancel() {
          state.Closeflow = true
          onSubmit()
        },
        class: 'test',
      });
    };

    const onSubmit = () => {
      validate().then(() => {
        state.submitLoading = true;
        let params = {
          bill_id: props.content.bill_id,
          middle_id: props.content.id,
          approval: state.processApprove,
          ...modelRef,
          needMsg: true,
        };
        params.cancel_match_date = moment(params.cancel_match_date).format(
            dateFormatStr
        );
        if (state.Closeflow) {
          params.close_stream = true
        }
        request.get("/org", "/bill/cancelMatch", params).then((res) => {
          message.success(res.msg || "取消成功！");
          context.emit("success");
        }).finally(() => {
          state.submitLoading = false;
        });
      });
    };

    const getSetting = () => {
      // 获取配置
      request.get("/org", "/approval/publish/process", {
        alias: 'bill_stream_cancel'
      }).then((res) => {
        state.processApprove = res.info.process    //判断是否开启
        state.Approveis_admin = res.info.is_admin    //判断是否有权限
        state.Approve_id = res.info.id
      });
    };

    const goSetting = () => {
      if (window.__MICRO_APP_ENVIRONMENT__) {

        window.microApp.forceDispatch({
          type: "SetChildDrawerList",
          info: {
            props: {
              title: "审批设置",
              maskCloseable: true,
              visible: true,
              closable: true,
              width: 1200,
              bodyStyle: {padding: 0, background: '#f7f7f7', height: '100%'},
              destroyOnClose: true,
            },
            microId: "approval_ApprovalSettings",
            app: "workApproval",
            url: '/approval/ApprovalSettings',
            params: {
              id: state.Approve_id,
              isMainDrawer: true,
              closeApproval: () => {
                getSetting()
              }
            }
          },

        })
      }

    };


    watch(
        () => props.visible,
        (val) => {
          if (val) {
            modelRef.cancel_match_date = moment(props.content.match_date);
          } else {
            resetFields();
            state.submitLoading = false;
          }
          getSetting();
        }
    );

    return {
      ...toRefs(state),
      dateFormatStr,
      modelRef,
      validateInfos,
      disabledDate,
      onCancel,
      onSubmit,
      getSetting,
      goSetting,
      showConfirm,
    };
  },
});
</script>
